<?php
class XorpayService
{
    private $url = 'http://xorpay.com/api';
    private $key;            // 填写通信密钥
    private $aid;          // 特写商户号
    private $body;          // 订单标题
    private $outTradeNo;          // 订单号
    private $openid;          // openid
    private $totalFee;          // 订单金额
    private $notifyUrl;          // 接收微信支付异步通知的回调地址
    private $payTip;          // 支付提示信息
    private $postUrl;
    private $payMode='NATIVE';		//支付模式
    public function __construct() {

    }
    public function setKey($key)
    {
        $this->key = $key;
    }
    public function setAid($aid)
    {
        $this->aid = $aid;
    }
    public function setBody($body)
    {
        $this->body = $body;
    }
    public function setOutTradeNo($outTradeNo)
    {
        $this->outTradeNo = $outTradeNo;
    }
    public function setTotalFee($totalFee)
    {
        $this->totalFee = $totalFee;
    }
    public function setNotifyUrl($notifyUrl)
    {
        $this->notifyUrl = $notifyUrl;
    }
    public function setPayTip($payTip)
    {
        $this->payTip = $payTip;
    }
    public function setOpenid($openid)
    {
        $this->openid = $openid;
    }
    public function setPostUrl($url)
    {
        $this->postUrl = $url;
    }
    public function setPayMode($mode)
    {
        $this->payMode = $mode;
    }

	public function getQrcode()
	{
		if($this->payMode=='alipay'){
			$response = $this->getPayQr('alipay');
		}else{
			$response = $this->getPayQr('native');
		}
		$responseArr = json_decode($response,true);
		$responseArr['out_trade_no'] = $this->outTradeNo;
		return json_encode($responseArr);
	}

    public function native(){
        $data = array(
            'price' => $this->totalFee,             // 金额,单位:分
            'order_id' => $this->outTradeNo,       // 订单号
            'name' => gbk2utf8($this->body),               // 订单标题
            'pay_type' => 'native',               // 订单标题
            'notify_url' => $this->notifyUrl,             // 回调地址
        );        
        $data['sign'] = $this->sign($data);
        return $this->curlPost($this->url.'/pay/'.$this->aid,$data);
    }
    /**
     * 跳转至二维码页面
     */
    public function gotoPay()
    {
		  global $cfg_phpurl;
        $domain = strpos($cfg_phpurl,'http')===0 ? $cfg_phpurl : getLocalDomain().$cfg_phpurl;
		return "<script>location.href='{$domain}/xorpay.php?out_trade_no={$this->outTradeNo}&total_fee={$this->totalFee}'</script>";		
    }


public function getAlipayH5Url()
    {
        $response = $this->getPayQr('alipay');
        $responseArr = json_decode($response,true);
        return "<script>location.href='".$responseArr['info']['qr']."'</script>";
    }

    
    /**
     * 跳转jsspi支付
     */
    public function jsapiPay()
    {
        $commonConfigs = array(
            'subject' => $this->body,               // 订单标题
            'out_trade_no' => $this->outTradeNo,       // 订单号
            'total_fee' => $this->totalFee,             // 金额,单位:元
            'jsapi' => $this->getJsApiParameters()
        );
        return $this->buildRequestForm($commonConfigs);
    }

    /**
     * jsapi支付
     * @return mixed
     */
    public function getJsApiParameters()
    {
        $url = $this->url.'/pay/'.$this->aid;
        $data['name'] =gbk2utf8($this->body);
        $data['price'] = $this->totalFee;
        $data['order_id'] = $this->outTradeNo;
        $data['pay_type'] ='jsapi';
        $data['notify_url'] = $this->notifyUrl;
        $data['openid'] = $this->openid;
        $data['sign'] = $this->sign($data);
        $result = $this->curlPost($url, $data);
        $result = json_decode($result,true);
        if($result['status']!='ok'){
            exit($result['status']);
        }
        return $result['info'];
    }

    /**
     * 支付宝当面付
     * @return mixed
     */
    public function getAlipayQr()
    {
        return $this->getPayQr('alipay');
    }

    public function getWeixinQr()
    {		
        return $this->getPayQr('native');
    }

	public function getPayQr($payType='alipay')
	{
		$url = $this->url.'/pay/'.$this->aid;		
        $data = array(
            'price' => $this->totalFee,             // 金额,单位:分
            'order_id' => $this->getOrderId(),       // 订单号
            'name' => gbk2utf8($this->body),               // 订单标题
            'pay_type' => $payType,               // 支付类型
            'notify_url' => $this->notifyUrl,             // 回调地址
        );        
        $data['sign'] = $this->sign($data);
        return $this->curlPost($url, $data);
	}

	public function getOrderId()
	{
		$new_trade_no = $this->outTradeNo;
		$f = substr($this->outTradeNo,-2);
		if($this->payMode=='alipay' && $f=='-W'){
			$new_trade_no = substr($this->outTradeNo,0,(strlen($this->outTradeNo)-2)).'-A';
		}elseif($this->payMode=='weixin' && $f=='-A'){
			$new_trade_no = substr($this->outTradeNo,0,(strlen($this->outTradeNo)-2)).'-W';
		}elseif($this->payMode=='alipay'){
			$new_trade_no = $this->outTradeNo.'-A';
		}elseif($this->payMode=='weixin'){
			$new_trade_no = $this->outTradeNo.'-W';
		}
		return $new_trade_no;
	}

    /**
     * 收银台支付
     * @return mixed
     */
    public function cashier()
    {
        $url = 'https://xorpay.com/api/cashier/'.$this->aid;
        $this->setPostUrl($url);
        $data['name'] =gbk2utf8($this->body);
        $data['price'] = $this->totalFee*100;
        $data['order_id'] = $this->outTradeNo;
        $data['pay_type'] ='jsapi';
        $data['notify_url'] = $this->notifyUrl;
        $data['return_url'] = '';
        $data['sign'] = $this->sign($data);
        $result = $this->buildRequestForm($data);
        echo $result;
        exit();
    }
    
public function getOpenid($backUrl='')
    {       
        if (!isset($_GET['openid'])) {
            
            //触发微信返回code码
            if(!$backUrl){
                $scheme = $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
                $uri = $_SERVER['PHP_SELF'] . $_SERVER['QUERY_STRING'];
                if ($_SERVER['REQUEST_URI']) $uri = $_SERVER['REQUEST_URI'];                
                $backUrl = $scheme . $_SERVER['HTTP_HOST'] . $uri;
            }
            $backUrl = str_replace('&','__',$backUrl);
            $backUrl = str_replace('?','?action=getOpenid__',$backUrl);
            $baseUrl = urlencode($backUrl);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();

    
        } else {
            return $_GET['openid'];
        }
    }

    public function __CreateOauthUrlForCode($url)
    {
        return $this->url.'/openid/'.$this->aid.'?callback='.$url;
    }
    /**
     * 建立请求，以表单HTML形式构造（默认）
     */
    protected function buildRequestForm($para_temp)
    {
        $action = $this->postUrl;
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='{$action}' method='POST'>";
        while (list ($key, $val) = each ($para_temp)) {
            $val = str_replace("'","&apos;",$val);
            $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
    public  function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public function sign(array $attributes) {

        $str = $attributes['name'].$attributes['pay_type'].$attributes['price'].$attributes['order_id'].$attributes['notify_url'].$this->key;
        $sign = md5($str);
        return $sign;
    }
    private function getHttpProtocol() {
        $protocol = 'http';
        if ( !empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            $protocol='https';
        } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
            $protocol='https';
        } elseif ( !empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            $protocol='https';
        }
        return $protocol;
    }
    public function check($data)
    {
        $_sign = $data['sign'];
        unset($data['sign']);
        $data['pay_price'] = trim($data['pay_price']);
        $sign = md5($data['aoid'].$data['order_id'].$data['pay_price'].$data['pay_time'].$this->key);
        return $sign==$_sign;
    }

}